<template>
  <!--音乐播放器组件-->
    <div class="my-footer">
        <!--原生音乐播放器部分-->
        <div v-show="false">
            <!--必须初始设置为muted才能自动播放-->
            <audio ref="musicPlayControl"
                   :src="musicState.url"
                   controls
                   :loop="musicState.playMood === 2"
                   @loadedmetadata="getMetadata"
                   @timeupdate="playTimeUpdate"
                   @canplaythrough="playMusic(false)"
                   @ended="playFinish">
                您的浏览器不支持音乐播放器
            </audio>
        </div>
        <!--音乐进度条-->
        <div class="play-slider">
            <el-slider v-model="musicState.currentTime"
                       :min="musicState.min"
                       :max="musicState.max"
                       :step="1"
                       :format-tooltip="formatSliderPlayTime"
                       @change="userChangeMusicTime"
                       @mousedown.native="musicState.sliderIsChange=true"
                       @mouseup.native="musicState.sliderIsChange=false">

            </el-slider>
        </div>
        <!-- 自定义音乐播放器组件-->
        <div class="my-audio">
            <div class="music-first">
                <div class="my-like" @click="likeMusic">
                    <el-image
                            :src="loadAssetsIcon(likeIcon.imgName)"
                            fit="cover"
                            :title="likeIcon.title">

                    </el-image>
                </div>
                <div class="music-info">
                    <span v-show="!musicState.isReady">正在加载...</span>
                    <span class="music-name" v-show="musicState.isReady">正在播放：{{ musicState.musicName }}</span>
                    <span class="music-name" v-show="musicState.isReady">正在播放：{{ musicState.musicName }}</span>
                </div>
            </div>
            <div class="music-play">
                <!-- 上一首按钮-->
                <div class="music-former" @click="btnChangeMusic(-1)">
                    <font-awesome-icon icon="fas fa-step-backward"/>
                </div>
                <!-- 播放按钮-->
                <div class="music-play-btn" @click="playMusic(!musicState.isPause)">
                    <font-awesome-icon icon="fas fa-play" v-show="musicState.isPause"/>
                    <font-awesome-icon icon="fas fa-pause" v-show="!musicState.isPause"/>
                </div>
                <!-- 下一首按钮-->
                <div class="music-next" @click="btnChangeMusic(1)">
                    <font-awesome-icon icon="fas fa-step-forward"/>
                </div>
            </div>
            <div class="music-fun">
                <!--播放列表按钮-->
                <div class="play-show-list" @click="showIsPlayingList">
                    <el-image
                            :src="loadAssetsIcon('playlist.png')"
                            fit="cover"
                            title="播放列表">

                    </el-image>
                </div>
                <div class="play-mood" @click="changePlayMood">
                    <el-image
                            :src="loadAssetsIcon(curPlayMood.imageName)"
                            fit="cover"
                            :title="curPlayMood.title">

                    </el-image>
                </div>
                <!-- 音乐声音部分-->
                <div class="play-volume">
                    <div class="volume-icon" @click="mutedVolume">
                        <font-awesome-icon :icon="volumeIcon"/>
                    </div>
                    <div class="volume-slider">
                        <el-slider v-model="volumeState.volume"
                                   :min="0"
                                   :max="100"
                                   :step="1"
                                   @change="volumeChange">

                        </el-slider>
                    </div>
                </div>
                <div class="show-play-detail">
                    <font-awesome-icon icon="fas fa-chevron-up"/>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import {publicFun} from "@/mixin";
import {randomChooseMusic, sequentialChooseMusic} from "@/http/tools";
import {CHANGEMUSICSTATE, HOTSONGSHOWBG, SHOWCURPLAYING, SHOWITEMBG} from "@/http/constant";

export default {
    name: "MusicPlay",
    mixins: [publicFun],
    data() {
        return {
            playMoodIcon: [
                {
                    imageName: 'Repeat.png',
                    title: '列表循环'
                },
                {
                    imageName: 'random.png',
                    title: '随机播放'
                },
                {
                    imageName: 'Repeat_.png',
                    title: '单曲循环'
                }
            ],
            curPlayMood: {
                imageName: 'Repeat.png',
                title: '列表循环'
            },
            likeIcon: {
                flag: false,
                imgName: 'heart_empty.png',
                title: '喜欢'
            },
            volumeIcons: ["fas fa-volume-mute", "fas fa-volume-down", "fas fa-volume-up"],
            musicState: {
                isReady: true,
                isPause: true,
                url: '',
                musicName: '',
                currentTime: 0,
                min: 0,
                max: 100,
                sliderIsChange: false,
                // 播放模式：0按顺序播放，1在当前歌单随机选择播放，2单曲循环
                playMood: 0
            },
            volumeState: {
                volume: 100,
                formerVolume: 100
            }
        }
    },
    methods: {
        // 初始化状态
        initState() {
            this.musicState = {
                isReady: false,
                isPause: true,
                url: '',
                musicName: '',
                currentTime: 0,
                min: 0,
                max: 100,
                sliderIsChange: false,
                playMood: 0
            }
            this.volumeState = {
                volume: 100,
                formerVolume: 100
            }
        },
        // 音乐状态
        likeMusic() {
            if (this.likeIcon.flag) {
                this.likeIcon = {
                    flag: false,
                    imgName: 'heart_empty.png',
                    title: '喜欢'
                }
            } else {
                this.likeIcon = {
                    flag: true,
                    imgName: 'heart_fill.png',
                    title: '不喜欢'
                }
            }
        },
        // 获取音乐的总时长
        getMetadata(e) {
            const {duration, volume} = e.target
            // 设置音频总时长
            this.$set(this.musicState, 'max', duration)
            // 设置当前音量
            this.$set(this.volumeState, 'volume', volume * 100)
            this.$set(this.volumeState, 'formerVolume', volume * 100)
        },
        // 音乐播放状态变化事件
        playMusic(flag) {
            // 修改播放状态为播放状态
            this.$set(this.musicState, 'isPause', flag)
        },
        // 时间更新事件
        playTimeUpdate(e) {
            const {currentTime} = e.target
            // 如果当前正在拖拽slider则不更新当前时间，避免在音乐播放的同时拖拽失效返回原位置
            if (!this.musicState.sliderIsChange) {
                // 设置slider的时间
                this.$set(this.musicState, 'currentTime', currentTime)
            }

        },
        // 格式化播放时间
        formatSliderPlayTime(val) {
            return this.formatMusicTime(val)
        },
        // 用户拖拽slider触发的事件
        userChangeMusicTime(val) {
            // 获取audio组件
            const {musicPlayControl} = this.$refs
            musicPlayControl.currentTime = val
        },
        volumeChange(val) {
            // 如果拖动后的音量不是0才会保存，如果是0就不保存以便于后边的静音按钮切换
            if (val) {
                // 同时也保存下来一份便于用户点击静音图标之后恢复之前的音量
                this.$set(this.volumeState, 'formerVolume', val)
            }
        },
        // 音量图标点击静音/不静音切换
        mutedVolume(e) {
            const {volume, formerVolume} = this.volumeState
            if (volume === 0) {
                this.$set(this.volumeState, 'volume', formerVolume)
            } else {
                // 静音
                this.$set(this.volumeState, 'volume', 0)
            }
        },
        /**
         * 提交更新当前播放的音乐
         * @param id
         */
        changeCurPlayingMusic(id) {
            this.$store.dispatch('updatePlaySongList', {
                // 选择播放的音乐id
                songId: id,
                isUpdatePlayingList: false,
            })
            this.$bus.$emit(SHOWITEMBG, {
                id
            })
            this.$bus.$emit(HOTSONGSHOWBG, {
                id
            })
        },
        // 音乐播放结束触发的事件
        playFinish() {
            // 播放结束时先暂停播放
            this.$set(this.musicState, 'isPause', true)
            // 获取播放列表以及当前播放的歌曲
            const {curPlayingMusic, playingSongList} = this.$store.state
            let music = {}
            if (this.musicState.playMood === 0) {
                music = sequentialChooseMusic(curPlayingMusic, playingSongList, 1)
            } else if (this.musicState.playMood === 1) {
                music = randomChooseMusic(curPlayingMusic, playingSongList)
            }
            if (this.musicState.playMood !== 2) {
                if (music) {
                    this.changeCurPlayingMusic(music.id)
                } else {
                    console.log(`当前播放列表为空`)
                }
            }
        },
        // 通过按钮切换歌曲
        btnChangeMusic(flag) {
            // 获取播放列表以及当前播放的歌曲
            const {curPlayingMusic, playingSongList, songList} = this.$store.state
            let music = {}
            if (this.musicState.playMood === 0) {
                music = sequentialChooseMusic(curPlayingMusic, songList, flag)
            } else if (this.musicState.playMood === 1) {
                music = randomChooseMusic(curPlayingMusic, playingSongList)
            }
            if (this.musicState.playMood !== 2) {
                if (music) {
                    this.changeCurPlayingMusic(music.id)
                } else {
                    console.log(`当前播放列表为空`)
                }
            }
        },
        // 切换播放模式
        changePlayMood() {
            this.$set(this.musicState, 'playMood', (this.musicState.playMood + 1) % 3)
        },
        // 显示音乐播放列表
        showIsPlayingList() {
            // 出发app.vue中显示当前播放列表
            this.$bus.$emit(SHOWCURPLAYING, {
                // 是否使用flag的值
                isUseFlag: false,
                flag: true
            })
        }
    },
    mounted() {
        this.$bus.$on(CHANGEMUSICSTATE, flag => {
            this.playMusic(flag)
        })
    },
    computed: {
        volumeIcon() {
            const icon = this.volumeIcons
            let index = 0
            if (this.volumeState.volume === 0) {
                index = 0
            } else if (this.volumeState.volume > 0 && this.volumeState.volume <= 50) {
                index = 1
            } else {
                index = 2
            }
            return icon[index]
        }
    },
    watch: {
        'musicState.isPause': {
            handler(newVal) {
                const {musicPlayControl} = this.$refs
                if (newVal && musicPlayControl.paused === false) {
                    musicPlayControl.pause()
                } else if (!newVal && musicPlayControl.paused === true) {
                    musicPlayControl.play()
                }
            }
        },
        'volumeState.volume': {
            handler(newVal) {
                const {musicPlayControl} = this.$refs
                musicPlayControl.volume = newVal / 100
            }
        },
        // 监听state中当前正在播放音乐切换
        '$store.state.curPlayingMusic': {
            deep: true,
            immediate: true,
            handler(newVal) {
                if (newVal.id < 0) {
                    // 初始化状态
                    this.initState()
                } else {
                    if (!newVal.success) {
                        let tmp = "正在播放下一首..."
                        if (newVal.url) {
                            tmp = '正在试听...'
                        }
                        // 没有版权
                        this.$message({
                            message: `${newVal.message},${tmp}`,
                            type: 'warning'
                        })
                    }
                    // console.log(newVal)
                    const singers = newVal.singers.length ? newVal.singers.map(item => {
                        return item.name
                    }) : ['']
                    // 当没有url的时候就播放下一首歌（暂时不能自动播放下一首）
                    if (newVal.url) {
                        this.musicState = {
                            ...this.musicState,
                            isReady: true,
                            isPause: true,
                            url: newVal.url,
                            musicName: `${newVal.musicName}-${singers.join(',')}`
                        }
                    } else {
                        this.musicState = {
                            ...this.musicState,
                            isReady: false,
                            isPause: true,
                            url: newVal.url,
                            musicName: `${newVal.musicName}-${singers.join(',')}`
                        }
                        // setTimeout(() => {
                        //     this.playFinish()
                        // }, 2000)
                    }
                }
            }
        },
        // 播放模式的切换
        'musicState.playMood': {
            immediate: true,
            handler(newVal) {
                this.curPlayMood = this.playMoodIcon[newVal]
            }
        }
    }
}
</script>

<style scoped lang="less">
@import "../assets/less/common";

@keyframes scrollInfinite {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(-100%);
  }
}

.my-footer {
  .play-slider {
    position: relative;
    transform: translateY(50%);
    padding: 0 .3vw;
    z-index: 99;
  }

  .my-audio {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    width: 100%;
    height: 64px;
    background-color: rgba(255, 255, 255, .5);
    //实现毛玻璃效果，但是需要背景颜色半透明
    backdrop-filter: saturate(180%) blur(25px);

    //喜欢按钮部分
    .music-first {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      height: 64px;
      width: 33%;

      .my-like {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 1.5vw;
        height: 1.5vw;


        > .el-image {
          width: 1vw;
          height: 1vw;
        }

        &:hover {
          background-color: @mouseHover;
          border-radius: 20%;
          cursor: pointer;
        }
      }

      .music-info {
        overflow: hidden;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        height: 64px;
        line-height: 64px;
        width: 10vw;
        margin-left: 8vw;
        font-weight: 700;

        .music-name {
          display: inline-block;
          white-space: nowrap;
          padding-right: 2vw;
          animation: scrollInfinite 10s linear infinite;
        }
      }
    }

    //音乐播放按钮部分
    .music-play {
      width: 34%;
      height: 64px;
      display: flex;
      align-items: center;
      justify-content: center;

      //播放按钮
      .music-play-btn {
        padding-left: .5vw;
        padding-right: .5vw;
        font-size: 2.5rem;

        &:hover {
          background-color: @mouseHover;
          border-radius: 20%;
          cursor: pointer;
        }
      }

      .music-former, .music-next {
        font-size: 2rem;
        padding: 0 .4vw;
        margin-left: 1vw;
        margin-right: 1vw;

        &:hover {
          background-color: @mouseHover;
          border-radius: 20%;
          cursor: pointer;
        }
      }
    }

    .music-fun {
      display: flex;
      margin-left: 5vw;
      justify-content: space-around;
      align-items: center;
      //background-color: red;
      width: 13vw;
      //音乐声音大小部分
      .play-volume {
        display: flex;
        width: 7vw;
        height: 64px;
        justify-content: space-between;
        align-items: center;

        .volume-icon {
          margin-right: 1rem;
          font-size: .85vw;
          padding: .2vw;

          &:hover {
            background-color: @mouseHover;
            border-radius: 20%;
            cursor: pointer;
          }
        }

        .volume-slider {
          width: 90%;
        }
      }

      //播放列表图标
      .play-show-list {
        width: 1.5vw;
        height: 1.5vw;
        padding: .2vw;

        &:hover {
          background-color: @mouseHover;
          border-radius: 20%;
          cursor: pointer;
        }
      }

      .play-mood {
        transform: translateY(3%);
        width: 1.5vw;
        height: 1.5vw;
        padding: .3vw;

        &:hover {
          background-color: @mouseHover;
          border-radius: 20%;
          cursor: pointer;
        }
      }

      .show-play-detail {
        font-size: 1vw;
        margin-left: 1vw;
        padding: .1vw .3vw;

        &:hover {
          background-color: @mouseHover;
          border-radius: 20%;
          cursor: pointer;
        }
      }
    }
  }
}
</style>